/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.domain.support;

import org.vacoor.nothing.web.domain.Pageable;
import org.vacoor.nothing.web.domain.Sort;

/**
 * 分页请求简单实现
 * 修改自 spring-data-common
 *
 * @author vacoor
 */
@SuppressWarnings("unused")
public class PageRequest implements Pageable {
    private static final long serialVersionUID = -4671969921304671061L;

    public static final int START_PAGE = 1;
    public static final int DEFAULT_PAGE = START_PAGE;
    public static final int DEFAULT_PAGE_SIZE = 20;
    public static final Sort EMPTY_SORT = new Sort();

    private int page;
    private int pageSize;
    private Sort sort;

    public PageRequest() {
        this(DEFAULT_PAGE, DEFAULT_PAGE_SIZE);
    }

    public PageRequest(int page, int pageSize) {
        this(page, pageSize, EMPTY_SORT);
    }

    public PageRequest(int page, int pageSize, Sort sort) {
        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than one!");
        }

        if (pageSize < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        }
        this.page = page > 0 ? page : DEFAULT_PAGE;
        this.pageSize = pageSize > 0 ? pageSize : DEFAULT_PAGE_SIZE;
        this.sort = sort != null ? sort : EMPTY_SORT;
    }

    public PageRequest(Pageable pageable) {
        this(pageable.getPage(), pageable.getPageSize(), pageable.getSort());
    }

    @Override
    public int getOffset() {
        return page > 0 ? (page - 1) * pageSize : 0;
    }

    @Override
    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page > 0 ? page : this.page;
    }

    @Override
    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize > 0 ? pageSize : this.pageSize;
    }

    @Override
    public Sort getSort() {
        return sort;
    }

    public void setSort(Sort sort) {
        this.sort = sort != null ? sort : EMPTY_SORT;
    }

    @Override
    public String toString() {
        return "PageRequest{" +
                "page=" + page +
                ", pageSize=" + pageSize +
                ", sort=" + sort +
                '}';
    }
}
